from django.contrib import admin
from django.db.models import Q
from requests import Response
from rest_framework import status
from django.forms import ModelForm

from databases.models import *


# Register your models here.

@admin.register(Training)
class TrainingAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        'introduce',
        'train_category',
        'background_image',
    )

    list_display_links = (
        'name',
        'background_image',
    )

    search_fields = [
        'name',
    ]
    exclude = ("browse_num", "join_num",)

    def train_category(self, obj):
        return obj.train_category.name

    train_category.short_description = "所属类别"


# admin.site.register(TrainCategory)


class ScriptForm(ModelForm):
    class Meta:
        model = TrainCategory
        fields = ('name', 'father')


@admin.register(TrainCategory)
class ScriptAdmin(admin.ModelAdmin):
    form = ScriptForm

    # inlines = (TrainCategory,)

    list_display = (
        'name',
        'get_father_name',
    )

    list_display_links = (
        'name',
    )

    search_fields = [
        'name',
    ]

    def get_father_name(self, obj):
        _father = obj.father
        if _father is not None:
            return _father.name
        else:
            return None

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'father':
            _path = request.META['PATH_INFO']
            _path1 = _path.replace('/admin/databases/traincategory/', '')
            _path2 = _path1.replace('/change/', '')
            kwargs['queryset'] = TrainCategory.objects.filter(~Q(pk=int(_path2)))
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    get_father_name.short_description = '上级类别名称'

    def save_model(self, request, obj, form, change):
        try:
            _father = obj.father
            if obj.id == _father.id:
                raise Exception('上级无法为自己')
            else:
                super().save_model(request, obj, form, change)
        except Exception as e:
            super().save_model(request, obj, form, change)

    def delete_model(self, request, obj):
        """

        :param request:
        :param obj:
        :return:
        """
        try:
            _sons = TrainCategory.objects.filter(father=obj)
            if len(_sons) > 0:
                raise Exception('该目录为非底层目录无法删除')
            else:
                obj.delete()
        except Exception as e:
            raise e


class InformationForm(ModelForm):
    class Meta:
        model = Information
        fields = (
            'info_title',
            'cover_image',
            'background_image',
            'info_text',
            'read_number',
        )


@admin.register(Information)
class InformationAdmin(admin.ModelAdmin):
    form = InformationForm

    # inlines = (TrainCategory,)

    list_display = (
        'info_title',
        'read_number',
        'cover_image',
    )

    list_display_links = (
        'info_title',
    )

    search_fields = [
        'info_title',
    ]

    readonly_fields = [
        'read_number',
    ]
